<?php
//Start session
if (!isset($_SESSION))
{
    session_start();
}

$cur_path = $_SERVER['SCRIPT_NAME'];
define("ADMIN_PATTERN", "/\/admin\/\b/");

$appendURL = "";
$adminURL = "admin/";

if(preg_match(ADMIN_PATTERN, $cur_path) == 1)
{
    $appendURL = "../";
    $adminURL = "";
}

//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['SESS_USER_ID']) || (trim($_SESSION['SESS_USER_ID']) == ''))
{
    // If user has a login cookie
    if(isset($_COOKIE['username']) && $_COOKIE['password'])
    {
        require_once('db_connect.php');

        //Connect to mysql server
        $connection = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
        if(!$connection)
        {
            die('Failed to connect to server: ' . mysql_error());
        }

        //Select database
        $db = mysql_select_db(DB_DATABASE);
        if(!$db)
        {
            die("Unable to select database");
        }
        $username = $_COOKIE['username'];
        $password = $_COOKIE['password'];
        $sql="SELECT * FROM dkp_users WHERE username='$username' AND password='$password'";
        $result=mysql_query($sql);

        if($result)
        {
            if(mysql_num_rows($result) == 1)
            {
                //Login Successful
                session_regenerate_id();
                $user = mysql_fetch_assoc($result);
                $_SESSION['SESS_USER_ID'] = $user['userid'];
                $_SESSION['SESS_USER_NAME'] = $user['username'];
                session_write_close();
                header("location: admin.php");
                exit();
            }
            else
            {
                //Login failed
                $_SESSION['LOGIN_ERR'] = "Please login first";
                session_write_close();
                header("location: " . $appendURL . "login.php");
                exit();
            }
        }
        else
        {
            die("Query failed");
        }
    }
    else
    {
        //Login failed
        $_SESSION['LOGIN_ERR'] = "Please login first";
        session_write_close();
        header("location: " . $appendURL . "login.php");
        exit();
    }
}

?>